#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <syslog.h>
#include <sys/socket.h>
#include <pthread.h>

#include "icar.h"
#include "icar_log.h"
#include "icar_msg.h"
#include "icar_utils.h"
#include "icar_thread.h"

int main(int argc, char **argv)
{
	int fd;
	int port = 7788;
	pthread_t tid;
	int result;

	fd = icar_create_server(SOCK_STREAM, port, NULL);
	if (fd < 0)
	{
		icar_daemon(LOG_ERR, "Create server failed");
		exit(1);
	}

	request *r = NULL;

	while (1) {
		r = icar_get_connection(fd, NULL);
		if (r)
		{
			void **params = icar_malloc(2 * sizeof(void *));
			*params = &fd;
			*(params+1) = r;
			result = pthread_create(&tid, NULL, (void *)thread_flat, (void *)params);
			if (result != 0)
				icar_die(_("FATAL: Failed to create a new thread server - exiting"));
			pthread_detach(tid);
		}
	}

	return 0;
}
